package com.truthbean.jutils.security;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import org.apache.log4j.Logger;

public class PasswordUtil {
    
    private final static Logger LOGGER = Logger.getLogger(PasswordUtil.class);

    /**
     * JAVA6支持以下任意一种算法 PBEWITHMD5ANDDES PBEWITHMD5ANDTRIPLEDES
     * PBEWITHSHAANDDESEDE PBEWITHSHA1ANDRC2_40 PBKDF2WITHHMACSHA1
	 *
     */
    /**
     * 定义使用的算法为:PBEWITHMD5andDES算法
     */
    private static final String ALGORITHM = "PBEWithMD5AndDES";//加密算法
    private static final String Salt = "abcdefgh";//密钥

    /**
     * 定义迭代次数为1000次
     */
    private static final int ITERATIONCOUNT = 1000;

    /**
     * 获取加密算法中使用的盐值,解密中使用的盐值必须与加密中使用的相同才能完成操作. 盐长度必须为8字节
     *
     * @return byte[] 盐值
	 *
     */
    public static byte[] getSalt() throws Exception {
        // 实例化安全随机数
        SecureRandom random = new SecureRandom();
        // 产出盐
        return random.generateSeed(8);
    }

    private static byte[] getStaticSalt() {
        // 产出盐
        return Salt.getBytes();
    }

    /**
     * 根据PBE密码生成一把密钥
     *
     * @param password 生成密钥时所使用的密码
     * @return Key PBE算法密钥
	 *
     */
    private static Key getPBEKey(String password) {
        // 实例化使用的算法
        SecretKeyFactory keyFactory;
        SecretKey secretKey = null;
        try {
            keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
            // 设置PBE密钥参数
            PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
            // 生成密钥
            secretKey = keyFactory.generateSecret(keySpec);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return secretKey;
    }

    /**
     * 加密明文字符串
     *
     * @param plaintext 待加密的明文字符串
     * @param password 生成密钥时所使用的密码
     * @param salt 盐值
     * @return 加密后的密文字符串
     * @throws Exception
     */
    private static String encrypt(String plaintext, String password, byte[] salt) {

        Key key = getPBEKey(password);
        byte[] encipheredData = null;
        PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, ITERATIONCOUNT);
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);

            cipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec);

            encipheredData = cipher.doFinal(plaintext.getBytes());
        } catch (Exception e) {
        }
        return bytesToHexString(encipheredData);
    }

    /**
     * 解密密文字符串
     *
     * @param ciphertext 待解密的密文字符串
     * @param password 生成密钥时所使用的密码(如需解密,该参数需要与加密时使用的一致)
     * @param salt 盐值(如需解密,该参数需要与加密时使用的一致)
     * @return 解密后的明文字符串
     * @throws Exception
     */
    private static String decrypt(String ciphertext, String password, byte[] salt) {

        Key key = getPBEKey(password);
        byte[] passDec = null;
        PBEParameterSpec parameterSpec = new PBEParameterSpec(getStaticSalt(), ITERATIONCOUNT);
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);

            cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);

            passDec = cipher.doFinal(hexStringToBytes(ciphertext));
        } catch (Exception e) {
            // TODO: handle exception
        }
        return new String(passDec);
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param src 字节数组
     * @return
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * 将十六进制字符串转换为字节数组
     *
     * @param hexString 十六进制字符串
     * @return
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static void main(String[] args) {
        int i = 10;
        for (int j = 0; j < i; j++) {
            if ((j) % 3 == 0) {
                System.out.print("<br>");
            } else {
                System.out.print(j);
            }
        }
        System.out.print(-1 % 2 == 0);
        String str = "123456789012345678901234567890123456789012345678901234567891234567890";
        String password = "123456";

        LOGGER.info("明文:" + str);
        LOGGER.info("密码:" + password);

        try {
            byte[] salt = PasswordUtil.getStaticSalt();
            String ciphertext = PasswordUtil.encrypt(str, password, salt);
            LOGGER.info("密文:" + ciphertext);
            String plaintext = PasswordUtil.decrypt(ciphertext, password, salt);
            LOGGER.info("明文:" + plaintext);
            System.out.println(ciphertext.length());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
    private static String dataPath = "D:/publicKey.data";

    /* public static void main(String[] args) throws Exception {  
	        //得到keyPairGenerator 的实例对象，并调用其generateKeyPair()方法得到KeyPair对象  
	        KeyPair keyPair= KeyPairGenerator.getInstance("RSA").generateKeyPair();  
	        publicKeyEncryption(keyPair);  
	        privateKeyEncryption(keyPair);  
	    } */

    private static void privateKeyEncryption(KeyPair keyPair) throws Exception {
        Cipher decryptionCipher = Cipher.getInstance("RSA");
        //调用KeyPair对象的getPrivate()，得到PrivateKey对象  
        PrivateKey privateKey = keyPair.getPrivate();
        //使用Cipher的实例对象，并调用其init()方法指定PublicKey对象，并指定进行加密操作  
        decryptionCipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] data = readData(dataPath);
        //调用Cipher对象的doFinal()方法完成解密操作。  
        byte[] result = decryptionCipher.doFinal(data);
        System.out.println("解密后的数据：" + new String(result, "UTF-8"));
    }

    private static void publicKeyEncryption(KeyPair keyPair) throws Exception {
        Cipher encryptionCipher = Cipher.getInstance("RSA");
        //调用KeyPair对象的getPublic()方法，得到PublicKey对象  
        PublicKey publicKey = keyPair.getPublic();
        String securityData = "私密数据";
        System.out.println("加密前的数据：" + securityData);
        //使用Cipher的实例对象，并调用其init()方法指定PrivateKey对象，并指定进行解密操作  
        encryptionCipher.init(Cipher.ENCRYPT_MODE, publicKey);
        //调用Cipher对象的doFinal()方法完成加密操作  
        byte[] result = encryptionCipher.doFinal(securityData.getBytes("UTF-8"));
        System.out.println("加密后的数据：" + new String(result, "UTF-8"));
        savaData(result, dataPath);

    }

    private static void savaData(byte[] data, String fileName) throws Exception {
        File file = new File(fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(data);
        fos.close();

    }

    private static byte[] readData(String fileName) throws Exception {
        File file = new File(fileName);
        FileInputStream fis = new FileInputStream(file);
        byte[] src = new byte[fis.available()];
        int len = 0;
        int total = 0;
        while (total < src.length) {
            total = total + len;
            len = fis.read(src, total, src.length - total);
        }
        fis.close();
        return src;
    }

}
